<template>
    <div class="MainBox">
        <el-card class="MainCard">
            <template #header>
                <div class="card-header">
                    <span>重置密码</span>
                </div>
            </template>
            <el-form :rules="passwordResetFormRules" :model="passwordResetForm" status-icon label-position="right"
                label-width="70px" ref="formRef">
                <el-form-item label="邮箱" prop="email">
                    <el-input type="text" v-model="passwordResetForm.email" />
                </el-form-item>
                <el-button type="primary" :disabled="getCaptchaButtonDisable" class="floatRight"
                    @click="getCaptchaByEmail()">
                    {{ buttonText }}
                </el-button>
                <el-form-item label="验证码" prop="captcha">
                    <el-input type="text" v-model="passwordResetForm.captcha" />
                </el-form-item>
                <el-form-item label="密码" prop="password" v-if="captchaGeted">
                    <el-input type="password" v-model="passwordResetForm.password" />
                </el-form-item>
                <el-form-item label="确认密码" prop="configurePassword" v-if="captchaGeted">
                    <el-input type="password" v-model="passwordResetForm.configurePassword" />
                </el-form-item>
                <el-button type="primary" v-if="captchaGeted" @click="passwordReset()">重置密码</el-button>
            </el-form>

        </el-card>
    </div>
</template>

<script>
import { flowerUserResetPassword, flowerUserExistsTest } from "@/api/flowerUser";
import { getCaptcha } from "@/api/email"
import { ElMessage } from 'element-plus';
import { jumpTo } from "@/utils/JumpDialog";
export default {
    name: 'PasswordResetting',
    data() {
        var validateConfigurePassword = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("请确认密码"));
            } else if (value !== this.passwordResetForm.password) {
                callback(new Error("两次密码不一致！"))
            } else {
                callback();
            }
        }
        return {
            getCaptchaButtonDisable: false,
            buttonText: '获取验证码',
            remainingTime: 30,
            captchaGeted: false,
            passwordResetForm: {
                id: '',
                email: '',
                captcha: '',
                password: '',
                configurePassword: '',
            },
            passwordResetFormRules: {
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                    {
                        type: 'email',
                        message: '请输入正确的邮箱格式',
                        trigger: ['blur', 'change']
                    },
                    {
                        validator: (rule, value, callback) => {
                            const params = {
                                email: value
                            };
                            flowerUserExistsTest(params).then(result => {
                                var findId = result.data.data
                                if (findId === 0) {
                                    callback("该邮箱未注册账号")
                                }
                                else {
                                    this.passwordResetForm.id = findId;
                                    callback()
                                }
                            })
                        },
                        trigger: 'blur'
                    },
                ],
                captcha: [
                    { required: true, message: '请输入验证码', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    {
                        pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,12}$/,
                        message: '密码需要同时包含英文字母和数字，且长度为8到12位',
                        trigger: 'blur'
                    }
                ],
                configurePassword: [
                    { validator: validateConfigurePassword, trigger: "blur", }
                ],
            }
        }
    },
    methods: {
        getCaptchaByEmail() {
            this.$refs.formRef.validateField('email', (valid) => {
                if (valid) {
                    // 如果没有错误消息，则表示 email 字段验证通过，可以执行获取验证码操作
                    const params = {
                        receiver: this.passwordResetForm.email
                    }
                    this.captchaGeted = true
                    this.getCaptchaButtonDisable = true
                    this.buttonText = `${this.remainingTime}秒后可再次发送`
                    let timer = setInterval(() => {
                        if (this.remainingTime > 1) {
                            this.remainingTime--
                            this.buttonText = `${this.remainingTime}秒后可再次发送`
                        } else {
                            this.getCaptchaButtonDisable = false
                            this.buttonText = '获取验证码'
                            this.remainingTime = 30
                            clearInterval(timer)
                        }
                    }, 1000)
                    getCaptcha(params)
                        .then((response) => {

                        })
                        .catch((error) => {
                            console.log(error);
                        })

                } else {
                    // 如果有错误消息，则表示 email 字段验证不通过
                }
            });
        },
        passwordReset() {
            this.$refs.formRef.validate((valid, error) => {
                if (valid) {
                    return flowerUserResetPassword(this.passwordResetForm)
                        .then((response) => {
                            ElMessage.success("密码重置成功")
                            jumpTo("重置成功","login",this.$route.name,3,"重置成功")
                        })
                        .catch((error) => {
                            ElMessage.error(error.response.data.data);
                        })
                }
            })
        }
    }
}
</script>

<style scoped>
.floatRight {
    float: right;
}

.MainBox {
    display: flex;
    justify-content: center;
    margin-top: 200px;
}

.MainCard {
    width: 400px;
}
</style>